package com.deep.bilibili.security;


import com.deep.bilibili.constant.CommonConstant;
import com.deep.bilibili.exception.ValidateCodeException;
import com.deep.bilibili.util.CodeUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class ValidateCodeFilter extends OncePerRequestFilter {

    private static Logger logger = LoggerFactory.getLogger(ValidateCodeFilter.class);

    @Autowired
    private CustomAuthenticationFailureHandler customAuthenticationFailureHandler;


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
//        logger.info("getRequestURI == {}", request.getRequestURI());
//        logger.info("getMethod == {}", request.getMethod());
        // 判断是登录 ，并且是post请求
        String requestMethod = request.getMethod();
        if (StringUtils.pathEquals("/admin/login", request.getRequestURI()) && "post".equalsIgnoreCase(requestMethod)) {

            try {
                validateCode(request);
                filterChain.doFilter(request, response);
            } catch (ValidateCodeException err) {
                logger.error("ValidateCodeException err = {}", err);
                customAuthenticationFailureHandler.onAuthenticationFailure(request, response, err);
//                throw new BadCredentialsException("验证码错误");
            } catch (BadCredentialsException err) {
                logger.error("BadCredentialsException err = {}", err);
                customAuthenticationFailureHandler.onAuthenticationFailure(request, response, err);
//                throw new BadCredentialsException("验证码错误");
            }
        } else {
            filterChain.doFilter(request, response);
        }
    }

    /**
     * 验证码
     * @param request
     * @throws ValidateCodeException
     */
    private void validateCode(HttpServletRequest request) throws ValidateCodeException {

        String captcha = request.getParameter(CommonConstant.KAPTCHA_SESSION_KEY);
        logger.info("validateCode captcha = {}", captcha);

        if (StringUtils.isEmpty(captcha)) {
            throw new ValidateCodeException("验证码不能为空");
        }

        //
        if (!CodeUtil.checkVerifyCode(request)) {
            throw new BadCredentialsException("验证码错误");
        }


    }

}
